<?php
// Include header
include 'header.php';

// 引入数据库类
require_once '../class/Database.php';

// 验证 AtomGit 仓库 URL
function isValidAtomGitURL($url) {
    return filter_var($url, FILTER_VALIDATE_URL) && preg_match('/^https?:\/\/atomgit\.com\/.+\/.+\.git$/', $url);
}

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $repo_url = trim($_POST['repo_url']);
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);

    // 验证用户输入
    if (empty($repo_url) || empty($name) || empty($email)) {
        $message = '所有字段都是必填项。';
    } elseif (!isValidAtomGitURL($repo_url)) {
        $message = '无效的 AtomGit 仓库 URL。';
    } else {
        // 实例化数据库类
        $db = new Database();

        // 检查是否已经签署
        $sql = "SELECT * FROM dco_signatures WHERE email = :email";
        $existing_user = $db->query($sql, ['email' => $email]);

        if ($existing_user) {
            $message = '您已经签署了 DCO。';
        } else {
            // 插入新的签署记录
            $insert_sql = "INSERT INTO dco_signatures (name, email, signed_at) VALUES (:name, :email, NOW())";
            if ($db->execute($insert_sql, ['name' => $name, 'email' => $email])) {
                $message = '感谢您的签署！';
            } else {
                $message = '签署过程中出现错误，请稍后再试。';
            }
        }
    }
}
?>

<!-- HTML 表单部分 -->
<h2>签署 DCO</h2>
<?php if ($message): ?>
    <div class="alert alert-info"><?= htmlspecialchars($message) ?></div>
<?php endif; ?>

<form method="POST" action="sign.php">
    <div class="form-group">
        <label for="repo_url">AtomGit 仓库 URL</label>
        <input type="text" class="form-control" id="repo_url" name="repo_url" required>
    </div>
    <div class="form-group">
        <label for="name">姓名</label>
        <input type="text" class="form-control" id="name" name="name" required>
    </div>
    <div class="form-group">
        <label for="email">电子邮件</label>
        <input type="email" class="form-control" id="email" name="email" required>
    </div>
    <button type="submit" class="btn btn-primary">提交签署</button>
</form>

<?php include 'footer.php'; ?>
